﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using NetTaste;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Logging;
using System.Linq.Expressions;
using NPOI.SS.Formula.Functions;
using DFGK_WMS.Model.Enum;
using Org.BouncyCastle.Asn1.Crmf;
using static Dm.parser.LVal;
using NPOI.Util;
using DFGK_WMS.Model.NoNet;
using Newtonsoft.Json;
using NPOI.XWPF.UserModel;
using NPOI.SS.UserModel;
using Microsoft.Data.Sqlite;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 出库管理
    /// </summary>
    public class TShippingOrderDetailRepository : BaseRepository<TShippingOrderDetail>, ITShippingOrderDetailRepository
    {
        private readonly ITShippingLockCellRepository lockCellRepository;
        private readonly SqliteContext sqlite;


        public TShippingOrderDetailRepository(DFGK_DB context, IMapper mapper, ITShippingLockCellRepository lockCellRepository, SqliteContext sqlite) : base(context, mapper)
        {
            this.lockCellRepository = lockCellRepository;
            this.sqlite = sqlite;
        }

        #region 添加出库单弃用
        /*
        /// <summary>
        /// 添加出库管理
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTShippingOrderDetail(TShippingOrderDetail model)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //订单号
                    //单据类型
                    //合同号
                    //物料分类 优先级为顶级 默认为0
                    //物料名称
                    var material = Context.TMaterials.Find(model.MaterialId);
                    if (material != null)
                    {
                        model.MaterialCode = material.Code;
                        model.MaterialName = material.Name;
                        model.MaterialTypeCode = material.TypeCode;
                        model.UnitId = material.UnitId;
                        model.UnitName = material.UnitName;
                    }

                    ////物料批次信息
                    //// 根据 MaterialId 和 MaterialName 查询对应的物料批次记录
                    //var materialkey = Context.TMaterialKeys.FirstOrDefault(m =>
                    //    m.MaterialId == model.MaterialId && m.MaterialName == model.MaterialName);
                    //if (materialkey != null)
                    //{
                    //    model.BatchNo = materialkey.BatchNo;
                    //}

                    //库房信息
                    var house = Context.TWarehouses.Find(model.WarehouseId);
                    if (house != null)
                    {
                        model.WarehouseCode = house.Code;
                        model.WarehouseName = house.Name;                      
                    }                

                    //出库数默认为0
                    model.PickedQty = model.Qty;
                    model.ShippedQty = 0;
                    model.Status = 0;
                    //部门
                    var userobj = Context.TUsers.Find(model.NowUserId);
                    if (userobj != null)
                    {
                        var deptobj = Context.TDepartments.Find(userobj.DepartmentId);
                        if (deptobj != null)
                        {
                            model.DeptName = deptobj.DepartmentName;
                            model.DeptCode = deptobj.DepartmentCode;
                        }
                    }

                    #region 审计字段

                    model.CreateUserId = model.NowUserId;
                    model.CreateUserName = model.NowUserRealName;
                    model.CreateDate = DateTime.Now;
                    model.ModifyUserId = model.NowUserId;
                    model.ModifyUserName = model.NowUserRealName;
                    model.ModifyDate = DateTime.Now;
                    model.AuditUserId = model.NowUserId;
                    model.AuditUserName = model.NowUserRealName;
                    model.AuditDate = DateTime.Now;
                    model.SubmitUserId = model.NowUserId;
                    model.SubmitUserName = model.NowUserRealName;
                    model.SubmitDate = DateTime.Now;

                    #endregion 审计字段

                    //供应商
                    var supper = Context.TSuppliers.Find(model.SupplierId);
                    if (supper != null)
                    {
                        model.SupplierName = supper.Name;
                    }
                
                    Context.TShippingOrderDetails.Add(model);
                    Context.SaveChanges();

                    

                    //货位锁定明细
                    foreach (var item in model.LockCell)
                    {
                        var inv = Context.TInventories.Where(s => s.Id == item.InventoryId).FirstOrDefault();
                        inv.Status = 4;
                        //item.AvailableQty = item.AvailableQty - item.OutQty;
                        Context.TInventories.Update(inv);
                        //货位锁定明细
                        TShippingLockCell m = new TShippingLockCell();
                        m.OrderDetailId = model.Id;
                        m.InventoryId = item.InventoryId;
                        m.CellId = item.CellId;
                        m.CellCode = item.CellCode;
                        m.CellName = item.CellName;
                        m.PalletBarcode = item.PalletBarcode;
                        m.WhId = model.WarehouseId;
                        m.CellDepthIndex = 0;
                        //组垛Id不知道
                        m.StackingStorageId = 0;
                        m.OutQty = item.OutQty;
                        m.InventoryQty = item.InventoryQty;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.MaterialKeyId = item.MaterialKeyId;
                        m.BatchNo = item.BatchNo;
                        m.CreateDate = DateTime.Now;
                        m.RoutewayId = item.RoutewayId;
                        Context.TShippingLockCells.Add(m);

                        // 添加货品表
                        TShippingGoodsDetail product = new TShippingGoodsDetail();
                        product.OrderDetailId = model.Id;
                        product.MaterialId = item.MaterialId;
                        product.MaterialCode = item.MaterialCode;
                        product.MaterialName = item.MaterialName;
                        product.Status = 0;
                        product.PalletBarcode = item.PalletBarcode;
                        Context.TShippingGoodsDetails.Add(product);

                        Context.SaveChanges();
                    }

                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 添加出库管理 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model,out string msg)
        {
            msg = "添加成功";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var mater in model.ShippingOrderDetailPlusLockCellDTOs)
                    {
          
                        //客户
                        var cust = Context.TCustomers.Find(model.CustomerId);
                        if (cust == null)
                        {
                            msg = "找不到客户";
                            return false;
                        }

                        //为了查询物料typeCode
                        var material = Context.TMaterials.Find(mater.MaterialId);
                        if (material == null)
                        {
                            msg = "找不到此物料";
                            return false;
                        }

                        var invmter = Context.TInventories.Where(s => s.MaterialId == mater.MaterialId);
                        if (invmter == null || invmter.Count() <= 0)
                        {
                            msg = "库存中没有此物料";
                            return false;
                        }

                        var invSum = GetMaterialIdById(mater.MaterialId).MaxCount;
                        if (mater.MaterialNum > invSum)
                        {
                            msg = mater.MaterialName + "库存数量不足，"+"最多可出"+ invSum;
                        }

                        var lockCell = lockCellRepository.LockCell(mater.MaterialId, mater.MaterialNum, out var lockCellList, out var errorMsg);
                        if (!lockCell)
                        {
                            return false;
                        }

                        TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
                        shippingOrderDetail.OrderSn = model.OrderSn; //同一个订单号
                        shippingOrderDetail.SupplierId = cust.Id;  // 拿供应商当客户用！
                        shippingOrderDetail.SupplierName=cust.Name;
                        shippingOrderDetail.MaterialId=mater.MaterialId;
                        shippingOrderDetail.MaterialName = mater.MaterialName;
                        shippingOrderDetail.MaterialTypeCode = material.TypeCode;
                        shippingOrderDetail.BillType = model.BillType;
                        shippingOrderDetail.WarehouseCode = "";
                        shippingOrderDetail.WarehouseName = "";
                        shippingOrderDetail.AreaCode = "";
                        shippingOrderDetail.AreaName = "";
                        shippingOrderDetail.BatchNo = "";
                        shippingOrderDetail.UnitName = material.UnitName;
                        shippingOrderDetail.Qty = mater.MaterialNum;
                        shippingOrderDetail.Status = 0 ;
                        shippingOrderDetail.StationName = "";
                        shippingOrderDetail.CreateDate = DateTime.Now;
                        shippingOrderDetail.CreateUserName = model.NowUserRealName;
                        shippingOrderDetail.CreateUserId = model.NowUserId;

                        
                        Context.TShippingOrderDetails.Add(shippingOrderDetail);
                        Context.SaveChanges();

                        // 添加货品表
                        TShippingGoodsDetail product = new TShippingGoodsDetail();
                        product.OrderDetailId = shippingOrderDetail.Id;
                        product.MaterialId = mater.MaterialId;
                        product.MaterialCode = mater.MaterialCode;
                        product.MaterialName = mater.MaterialName;
                        product.Status = 0;
                        Context.TShippingGoodsDetails.Add(product);
                        Context.SaveChanges();

                        //货位锁定明细
                        foreach (var item in lockCellList)
                        {
                            var inv = Context.TInventories.Where(s => s.Id == item.InventoryId).FirstOrDefault();
                            if (inv == null)
                                return false;
                            inv.Status = 4;
                            Context.TInventories.Update(inv);
                            //货位锁定明细
                            TShippingLockCell m = new TShippingLockCell();
                            m.OrderDetailId = shippingOrderDetail.Id;
                            m.InventoryId = item.InventoryId;
                            m.CellId = item.CellId;
                            m.CellCode = item.CellCode;
                            m.CellName = item.CellName;
                            m.PalletBarcode = item.PalletBarcode;
                            m.WhId = item.WhId;
                            m.CellDepthIndex = 0;
                            m.StackingStorageId = item.StackingStorageId;
                            m.OutQty = item.OutQty;
                            m.InventoryQty = item.InventoryQty;
                            m.MaterialId = item.MaterialId;
                            m.MaterialName = item.MaterialName;
                            m.MaterialCode = item.MaterialCode;
                            m.MaterialKeyId = item.MaterialKeyId;
                            m.BatchNo = item.BatchNo;
                            m.CreateDate = DateTime.Now;
                            m.RoutewayId = item.RoutewayId;
                            m.IsPicking = false;
                            Context.TShippingLockCells.Add(m);
                            Context.SaveChanges();
                        }
                    }
                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }
                */
        #endregion

        /// <summary>
        /// 往sqlite中写入数据
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool AddSqliteDetail(GroupShippingOrderDto m, int id, out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                //创建表（如果不存在）
                bool aa = sqlite.Database.EnsureCreated();
                // 设置连接字符串
                string connectionString = "Data Source=.\\wwwroot\\file\\chat.db";

                // 创建连接对象
                using (var connection = new SqliteConnection(connectionString))
                {
                    // 打开连接
                    connection.Open();

                    // 创建SQL命令对象
                    using (var command = connection.CreateCommand())
                    {
                        // 设置清空缓存的SQL语句
                        command.CommandText = "PRAGMA cache_size=0;";

                        // 执行SQL命令
                        command.ExecuteNonQuery();

                        Console.WriteLine("Cache cleared.");
                    }

                    // 关闭连接
                    connection.Close();
                }
                if (m.shippingLockCells.Count() > 0)
                {
                    List<SqliteChildrenShippingOrder> childrenss = new List<SqliteChildrenShippingOrder>();
                    foreach (var item in m.shippingLockCells)
                    {
                        SqliteChildrenShippingOrder childrens = new SqliteChildrenShippingOrder();
                        childrens.MakerialCategoryId = item.MaterialCategoryId;
                        childrens.MaterialCategoryName = item.MaterialCategoryName;
                        //childrens.MaterialId = item.MaterialId;
                        childrens.Name = item.MaterialName;
                        childrens.Code = item.MaterialCode;
                        childrens.ModelSpec = item.ModelSpec;
                        childrens.QualityState = item.QualityState;
                        childrens.Price = item.Price;
                        childrens.Price = item.Price;
                        childrens.Measurement = item.UnitName;
                        childrens.Qty = item.InventoryQty;
                        childrens.TotalPrice = item.TotalPrice;


                    }

                    var Json = JsonConvert.SerializeObject(m.shippingLockCells);


                    var OutboundListModes = new OutboundListModes()
                    {
                        OrderSn = m.OrderSn,
                        RelevanceOrderSn = m.RelevanceOrderSn,
                        BillType = m.BillType,
                        Agent = m.Agent,
                        SupplierId = m.SupplierId,
                        SupplierCode = m.SupplierCode,
                        SupplierName = m.SupplierName,
                        Contact = m.Contact,
                        ContactMobile = m.ContactMobile,
                        ProductDate = m.ProductDate,
                        NowUserId = m.NowUserId,
                        NowUserName = m.NowUserName,
                        State = m.State,
                        Remark = m.Remark,
                        JsonData = Json
                    };

                    var shippingList = Context.TShippingOrderDetails.Where(x => x.OrderSn == m.OrderSn).ToList();
                    foreach (var item in shippingList)
                    {
                        item.Status = 1;
                        Context.TShippingOrderDetails.Update(item);
                        if(Context.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            message = "修改出库单状态失败";
                            return false;
                        }
                    }

                    string OrderSnByError = "";
                    List<ShippingQueryTable> shippingQueryTable = new List<ShippingQueryTable>();
                    List<SqliteChildrenShippingOrder> dataList = JsonConvert.DeserializeObject<List<SqliteChildrenShippingOrder>>(OutboundListModes.JsonData).ToList();
                    // foreach (var Details in dataList)
                    // {
                    //var ShippingList = Context.TShippingGoodsDetails.Where(x => x.OrderDetailId == Details.Id).ToList();
                    var ShippingList = Context.TShippingLockCells.Where(x => x.OrderDetailId == id).ToList();
                    foreach (var item in ShippingList)
                    {
                        //sqlite.SubmitReceiving.Where(x => x.BarCode == BarCode);
                        var newShippingQueryTable = new ShippingQueryTable(); // 创建一个新的 ShippingQueryTable 对象
                        newShippingQueryTable.OrderSn = m.OrderSn;
                        OrderSnByError = m.OrderSn;
                        newShippingQueryTable.OrderSnDetailId = item.Id;
                        newShippingQueryTable.MaterialName = item.MaterialName;
                        newShippingQueryTable.MaterialCategoryName = item.MaterialCategoryName;
                        newShippingQueryTable.QualityState = item.QualityState;
                        newShippingQueryTable.InventoryQty = m.shippingLockCells.Where(x => x.MaterialCode == item.MaterialCode).Sum(x => x.InventoryQty);
                        newShippingQueryTable.OutQty = item.OutQty;
                        newShippingQueryTable.CellName = Context.TInventories.Where(x => x.MaterialCode == item.MaterialCode).First().LocationCode;

                        //newShippingQueryTable.BarCode = item.Barcode;

                        shippingQueryTable.Add(newShippingQueryTable);

                    }
                    //}
                    sqlite.ShippingQueryTable.AddRange(shippingQueryTable);
                    sqlite.OutboundListModes.Add(OutboundListModes);

                    if (sqlite.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        message = "出库数据添加失败!单号:" + OrderSnByError;
                        return false;
                    }

                    //Console.Write("Json==========================================================="+InboundListMode.jsonData);

                    if (OutboundListModes == null)
                    {
                        tran.Rollback();
                        message = "出库数据添加失败";
                        return false;
                    }
                    tran.Commit();
                    message = "出库数据添加成功！";
                    return true;
                }
                else
                {
                    var OutboundListModes = new OutboundListModes()
                    {
                        OrderSn = m.OrderSn,
                        RelevanceOrderSn = m.RelevanceOrderSn,
                        BillType = m.BillType,
                        Agent = m.Agent,
                        SupplierId = m.SupplierId,
                        SupplierCode = m.SupplierCode,
                        SupplierName = m.SupplierName,
                        Contact = m.Contact,
                        ContactMobile = m.ContactMobile,
                        ProductDate = m.ProductDate,
                        NowUserId = m.NowUserId,
                        NowUserName = m.NowUserName,
                        State = m.State,
                        Remark = m.Remark,
                        JsonData = null
                    };

                    string OrderSnByError = "";
                    List<ShippingQueryTable> shippingQueryTable = new List<ShippingQueryTable>();
                  
                    sqlite.ShippingQueryTable.AddRange(shippingQueryTable);
                    sqlite.OutboundListModes.Add(OutboundListModes);

                    if (sqlite.SaveChanges() <= 0)
                    {
                        tran.Rollback();
                        message = "出库数据添加失败!单号:" + OrderSnByError;
                        return false;
                    }

                    //Console.Write("Json==========================================================="+InboundListMode.jsonData);

                    if (OutboundListModes == null)
                    {
                        tran.Rollback();
                        message = "出库数据添加失败";
                        return false;
                    }
                    tran.Commit();
                    message = "出库数据添加成功！";
                    return true;

                }
                

            }
            catch
            {
                tran.Rollback();
                message = "出库数据添加失败！";
                return false;
            }




        }

        /// <summary>
        /// 在sqlite中获取数据
        /// </summary>
        /// <returns></returns>
        public List<GroupShippingOrderDto> GetShippingOrderDtos()
        {
            //创建表（如果不存在）
            sqlite.Database.EnsureCreated();

            var list = sqlite.OutboundListModes.AsQueryable();

            List<GroupShippingOrderDto> dto = new List<GroupShippingOrderDto>();
            foreach (var order in list)
            {
                GroupShippingOrderDto groupShippingOrder = new GroupShippingOrderDto();
                groupShippingOrder.BillType = order.BillType;
                groupShippingOrder.OrderSn = order.OrderSn;
                groupShippingOrder.RelevanceOrderSn = order.RelevanceOrderSn;
                groupShippingOrder.Agent = order.Agent;
                groupShippingOrder.SupplierId = order.SupplierId;
                groupShippingOrder.SupplierCode = order.SupplierCode;
                groupShippingOrder.SupplierName = order.SupplierName;
                groupShippingOrder.Contact = order.Contact;
                groupShippingOrder.ContactMobile = order.ContactMobile;
                groupShippingOrder.ProductDate = order.ProductDate;
                groupShippingOrder.ShippingVoucher = order.ShippingVoucher;
                groupShippingOrder.NowUserId = order.NowUserId;
                groupShippingOrder.NowUserName = order.NowUserName;
                groupShippingOrder.State = order.State;
                groupShippingOrder.Remark = order.Remark;
                //groupShippingOrder.ExamineState = order.ExamineState;

                List<TShippingLockCell> JsonList = JsonConvert.DeserializeObject<List<TShippingLockCell>>(order.JsonData);
                groupShippingOrder.shippingLockCells = JsonList;
                dto.Add(groupShippingOrder);

            }

            return dto;
        }

        /// <summary>
        /// 通过出库单号获取数据
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public GroupShippingOrderDto GetGroupShippingOrderDtoByOrdersn(string OrderSn)
        {
            var receorder = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();
            if (!receorder.Any())
            {
                return null;
            }
            GroupShippingOrderDto groupShippingOrderDto = new GroupShippingOrderDto();
            groupShippingOrderDto.Id = receorder.First().Id;
            groupShippingOrderDto.OrderSn = receorder.First().OrderSn;
            groupShippingOrderDto.BillType = receorder.First().BillType;
            groupShippingOrderDto.RelevanceOrderSn = receorder.First().RelevanceOrderSn;
            groupShippingOrderDto.Agent = receorder.First().Agent;
            groupShippingOrderDto.SupplierId = receorder.First().SupplierId;
            groupShippingOrderDto.SupplierName = receorder.First().SupplierName;
            groupShippingOrderDto.SupplierCode = receorder.First().SupplierCode;
            groupShippingOrderDto.Contact = receorder.First().Contact;
            groupShippingOrderDto.ContactMobile = receorder.First().ContactMobile;
            groupShippingOrderDto.ProductDate = receorder.First().CreateDate;
            groupShippingOrderDto.Remark = receorder.First().Remark;
            groupShippingOrderDto.State = receorder.First().Status;
            groupShippingOrderDto.ShippingVoucher = receorder.First().ShippingVoucher;

            var tshiLock = Context.TShippingLockCells.Where(x => x.OrderDetailId == groupShippingOrderDto.Id);
            foreach (var item in tshiLock)
            {
                TShippingLockCell shipping = new TShippingLockCell();
                shipping.Id = item.Id;
                shipping.MaterialCategoryId = item.MaterialCategoryId;
                shipping.MaterialCategoryName = item.MaterialCategoryName;
                shipping.MaterialId = item.MaterialId;
                shipping.MaterialName = item.MaterialName;
                shipping.MaterialCode = item.MaterialCode;
                shipping.ModelSpec = item.ModelSpec;
                shipping.QualityState = item.QualityState;
                shipping.Price = item.Price;
                shipping.OutQty = item.OutQty;
                shipping.InventoryQty = item.InventoryQty;
                shipping.TotalPrice = item.TotalPrice;
                shipping.UnitName = item.UnitName;
                groupShippingOrderDto.shippingLockCells.Add(shipping);

            }
            return groupShippingOrderDto;
        }


        /// <summary>
        /// 提交按钮
        /// </summary>
        /// <returns></returns>
        public bool submitShipping(out string message)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                message = "";
                //创建表（如果不存在）
                sqlite.Database.EnsureCreated();

                var list = sqlite.SubmitShipping.AsQueryable();

                if (list == null || !list.Any())
                {
                    message = "出库单未查询到数据";
                    return false;
                }
                string OrderSn = "";//初始单号
                string OrderSnDouble = "";//当前单号
                string OrderSnThree = "";//上个单号
                List<GroupShippingOrderDto> dto = new List<GroupShippingOrderDto>();


                string OrdeSnByError = "";
                int y = 0;
                foreach (var order in list)
                {

                    var listCount = list.Select(x => x.OrderSn).Count();
                    GroupShippingOrderDto groupShippingOrderDto = new GroupShippingOrderDto();
                    TShippingLockCell shippingLockCell = new TShippingLockCell();

                    groupShippingOrderDto.OrderSn = order.OrderSn;
                    OrdeSnByError = order.OrderSn;
                    OrderSn = list.First().OrderSn;
                    OrderSnDouble = order.OrderSn;
                    shippingLockCell.OutQty = order.Qty;
                    shippingLockCell.CellCode = order.Position;

                    //var Tshipping1 = Context.TShippingOrderDetails.AsNoTracking().AsQueryable();
                    //Tshipping1 = Tshipping1.Where(x => x.OrderSn == order.OrderSn);
                    //var ShippingList = Tshipping1.Skip((i - 1) * 1).Take(1).FirstOrDefault();
                    var ShippingList = Context.TShippingOrderDetails.Where(x => x.OrderSn == order.OrderSn).ToList();
                    foreach (var item in ShippingList)
                    {

                        if (order.MaterialCode != "undefined")
                        {
                            var InventoryList = Context.TInventories.Where(x => x.MaterialCode == order.MaterialCode);
                            var MaterialListAll = Context.TMaterial.Where(x => x.Code == order.MaterialCode);
                            if(MaterialListAll.Count() <= 0)
                            {
                                message = "请求物料编码有误";
                                tran.Rollback();
                                return false;
                            }
                            var MaterialList = MaterialListAll.First(x => x.Code == order.MaterialCode);
                            TShippingLockCell shippingLockCell1 = new TShippingLockCell();
                            shippingLockCell.OrderDetailId = Context.TShippingOrderDetails.First(x => x.OrderSn == order.OrderSn).Id;
                            shippingLockCell.OutQty = order.Qty;
                            shippingLockCell.InventoryQty = InventoryList.Count(x => x.AvailableQty != 0);
                            shippingLockCell.MaterialId = MaterialList.Id;
                            shippingLockCell.MaterialCode = MaterialList.Code;
                            shippingLockCell.MaterialName = order.MaterialName;
                            shippingLockCell.MaterialCategoryId = MaterialList.MaterialCategoryId;
                            shippingLockCell.MaterialCategoryCode = MaterialList.MaterialCategoryCode;
                            shippingLockCell.MaterialCategoryName = MaterialList.MaterialCategoryName;
                            shippingLockCell.UnitId = MaterialList.UnitId;
                            shippingLockCell.UnitName = MaterialList.UnitName;
                            shippingLockCell.ModelSpec = MaterialList.ModelSpec;
                            shippingLockCell.QualityState = MaterialList.QualityState;
                            shippingLockCell.Price = InventoryList.First(x => x.MaterialCode == MaterialList.Code).Price;
                            shippingLockCell.TotalPrice = order.Qty * shippingLockCell.Price;
                            shippingLockCell.MaterialGroupCode = MaterialList.MaterialGroupCode;
                            Context.TShippingLockCells.Add(shippingLockCell);
                            if (Context.SaveChanges() <= 0)
                            {
                                message = "添加出库明细失败";
                                tran.Rollback();
                                return false;
                            }
                        }
                        var ShippingLock = Context.TShippingLockCells.Where(x => x.OrderDetailId == item.Id && x.MaterialName == order.MaterialName).ToList();

                        groupShippingOrderDto.BillType = item.BillType;
                        groupShippingOrderDto.Agent = item.Agent;
                        groupShippingOrderDto.SupplierId = item.SupplierId;
                        groupShippingOrderDto.SupplierCode = item.SupplierCode;
                        groupShippingOrderDto.SupplierName = item.SupplierName;
                        groupShippingOrderDto.Contact = item.Contact;
                        groupShippingOrderDto.ContactMobile = item.ContactMobile;
                        groupShippingOrderDto.ProductDate = item.CreateDate;
                        groupShippingOrderDto.Remark = item.Remark;
                        groupShippingOrderDto.NowUserId = item.NowUserId;
                        groupShippingOrderDto.NowUserName = item.NowUserRealName;
                        shippingLockCell.MaterialCode = ShippingLock.FirstOrDefault().MaterialCode;
                        groupShippingOrderDto.shippingLockCells.Add(shippingLockCell);
                        dto.Add(groupShippingOrderDto);
                        // ;

                        var existingOrder = sqlite.OutboundListModes.FirstOrDefault(o => o.OrderSn == item.OrderSn);

                        //if (existingOrder != null && existingOrder.State == 4)
                        //{

                        //    sqlite.OutboundListModes.Remove(existingOrder);
                        //    if (sqlite.SaveChanges() <= 0)
                        //    {
                        //        tran.Rollback();
                        //        message = "删除OutboundListModes表数据失败!";
                        //        return false;
                        //    }
                        //}

                    }
                    y++;
                    if (OrderSnThree != "" && OrderSnDouble != OrderSnThree)
                    {
                        var shippingList = sqlite.SubmitShipping.Where(x => x.OrderSn == OrderSnThree).ToList();
                        sqlite.SubmitShipping.RemoveRange(shippingList);
                        var queryShippingList = sqlite.ShippingQueryTable.Where(x => x.OrderSn == OrderSnThree).ToList();
                        sqlite.ShippingQueryTable.RemoveRange(queryShippingList);
                        var shippingModesList = sqlite.OutboundListModes.Where(x => x.OrderSn == OrderSnThree).ToList();
                        sqlite.OutboundListModes.RemoveRange(shippingModesList);
                        if (sqlite.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            message = "出库数据更新失败!";
                            return false;
                        }

                    }

                    if (listCount == y)
                    {
                        var shippingList = sqlite.SubmitShipping.Where(x => x.OrderSn == OrderSnDouble).ToList();
                        sqlite.SubmitShipping.RemoveRange(shippingList);
                        var queryShippingList = sqlite.ShippingQueryTable.Where(x => x.OrderSn == OrderSnDouble).ToList();
                        sqlite.ShippingQueryTable.RemoveRange(queryShippingList);
                        var shippingModesList = sqlite.OutboundListModes.Where(x => x.OrderSn == OrderSnDouble).ToList();
                        sqlite.OutboundListModes.RemoveRange(shippingModesList);
                        if (sqlite.SaveChanges() <= 0)
                        {
                            tran.Rollback();
                            message = "出库数据更新失败!";
                            return false;
                        }

                    }

                    OrderSnThree = order.OrderSn;
                }

                int i = 1;

              

                foreach (var item in dto)
                {
                    // 减库存
                    var TInventoryList = Context.TInventory.Where(x => x.MaterialCode == item.shippingLockCells[0].MaterialCode).ToList();
                    if (TInventoryList.Count() == 0)
                    {
                        tran.Rollback();
                        message = "未查询到出库单中添加的物料! 物料编码:" + TInventoryList[0].MaterialCode;
                        return false;
                    }
                    TInventoryLog inventory = new TInventoryLog();
                    inventory.SourceType = 1;
                    inventory.SourceSn = item.OrderSn;
                    inventory.WarehouseId = TInventoryList[0].WarehouseId;
                    inventory.WarehouseName = TInventoryList[0].WarehouseName;
                    inventory.LocationCode = TInventoryList[0].LocationCode;
                    inventory.PalletBarcode = TInventoryList[0].PalletBarcode;
                    inventory.MaterialId = TInventoryList[0].MaterialId;
                    inventory.MaterialCode = TInventoryList[0].MaterialCode;
                    inventory.MaterialName = TInventoryList[0].MaterialName;
                    inventory.BaseUnitId = TInventoryList[0].UnitId;
                    inventory.BaseUnitName = TInventoryList[0].UnitName;
                    //原始数量
                    inventory.StartQty = TInventoryList[0].AvailableQty;
                    //变更数量
                    inventory.ChangeQty = item.shippingLockCells[0].OutQty;
                    TInventoryList[0].AvailableQty = TInventoryList[0].AvailableQty -= item.shippingLockCells[0].OutQty;
                    //最终数量
                    inventory.EndQty = TInventoryList[0].AvailableQty;
                    inventory.CreateDate = DateTime.Now;
                    inventory.CreateUserId = item.CreateUserId;
                    inventory.CreateUser = item.CreateUserName;
                    //var WarningRolesList = Context.TWarningRules.First(x => x.MaterialCode == TInventoryList[0].MaterialCode);
                    //if (TInventoryList[0].AvailableQty < WarningRolesList.WarningQtyMin)
                    //{
                    //    TInventoryWarn inventoryWarnModel = new TInventoryWarn();
                    //    inventoryWarnModel.MaterialId = TInventoryList[0].MaterialId;
                    //    inventoryWarnModel.MaterialCode = TInventoryList[0].MaterialCode;
                    //    inventoryWarnModel.MaterialName = TInventoryList[0].MaterialName;
                    //    inventoryWarnModel.MaterialTypeName = TInventoryList[0].MaterialTypeName;
                    //    inventoryWarnModel.WarnType = 1;
                    //    inventoryWarnModel.QTY = TInventoryList[0].AvailableQty;
                    //    Context.TInventoryWarn.Add(inventoryWarnModel);
                    //}

                    IsInventoryWarn(TInventoryList);

                    Context.TInventoryLogs.Add(inventory);
                    if (TInventoryList[0].AvailableQty <= 0)
                    {
                        Context.TInventories.Remove(TInventoryList[0]);
                        var MaterialList = Context.TMaterial.First(x => x.Code == inventory.MaterialCode);
                        Context.TMaterial.Remove(MaterialList);
                    }

                    var ShippingOrderDetailList = Context.TShippingOrderDetails.FirstOrDefault(x => x.OrderSn == item.OrderSn);
                    if (ShippingOrderDetailList == null)
                    {
                        tran.Rollback();
                        message = "出库单明细不存在! 单号:" + item.OrderSn;
                        return false;
                    }
                    if (i == 1)
                    {
                        ShippingOrderDetailList.Status = 4;
                        Context.TShippingOrderDetails.Update(ShippingOrderDetailList);


                    }
                    i++;

                }

                if (Context.SaveChanges() <= 0)
                {
                    tran.Rollback();
                    message = "出库减去库存失败！";
                    return false;
                }
                tran.Commit();
                message = "出库减去库存成功！";
                return true;



            }
            catch
            {
                tran.Rollback();
                message = "出库修改库存状态失败!";
                return false;
            }

        }


        /// <summary>
        /// 封装方法
        /// </summary>
        /// <param name="inventories"></param>
        /// <returns></returns>
        public bool IsInventoryWarn(List<TInventory> inventories)
        {
            try
            {
                var WarningRolesList = Context.TWarningRules.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                if (WarningRolesList == null || WarningRolesList.Count() <= 0)
                {
                    return false;
                }

                if (inventories[0].AvailableQty > WarningRolesList.First().WarningQtyMax)
                {
                    var InventoryWarn = Context.TInventoryWarn.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                    if (InventoryWarn == null || InventoryWarn.Count() <= 0)
                    {
                        TInventoryWarn inventoryWarnModel = new TInventoryWarn();
                        inventoryWarnModel.MaterialId = inventories[0].MaterialId;
                        inventoryWarnModel.MaterialCode = inventories[0].MaterialCode;
                        inventoryWarnModel.MaterialName = inventories[0].MaterialName;
                        inventoryWarnModel.MaterialTypeName = inventories[0].MaterialTypeName;
                        inventoryWarnModel.WarnType = 2;
                        inventoryWarnModel.QTY = inventories[0].AvailableQty;
                        Context.TInventoryWarn.Add(inventoryWarnModel);
                    }
                    else
                    {
                        //InventoryWarn.First().MaterialId = inventories[0].MaterialId;
                        //InventoryWarn.First().MaterialCode = inventories[0].MaterialCode;
                        //InventoryWarn.First().MaterialName = inventories[0].MaterialName;
                        //InventoryWarn.First().MaterialTypeName = inventories[0].MaterialTypeName;
                        InventoryWarn.First().QTY = inventories[0].AvailableQty;
                        InventoryWarn.First().WarnType = 2;
                        Context.TInventoryWarn.Update(InventoryWarn.First());
                    }
                    if (Context.SaveChanges() <= 0)
                    {
                        return false;
                    }

                }
                else if (inventories[0].AvailableQty < WarningRolesList.First().WarningQtyMax && inventories[0].AvailableQty > WarningRolesList.First().WarningQtyMin)
                {
                    var InventoryWarn = Context.TInventoryWarn.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                    if (InventoryWarn.Count() < 0)
                    {
                        Context.TInventoryWarn.Remove(InventoryWarn.First());
                        if (Context.SaveChanges() <= 0)
                        {
                            return false;
                        }
                    }

                }
                else if (inventories[0].AvailableQty < WarningRolesList.First().WarningQtyMin)
                {
                    var InventoryWarn = Context.TInventoryWarn.Where(x => x.MaterialCode == inventories[0].MaterialCode);
                    if (InventoryWarn == null || InventoryWarn.Count() <= 0)
                    {
                        TInventoryWarn inventoryWarnModel = new TInventoryWarn();
                        inventoryWarnModel.MaterialId = inventories[0].MaterialId;
                        inventoryWarnModel.MaterialCode = inventories[0].MaterialCode;
                        inventoryWarnModel.MaterialName = inventories[0].MaterialName;
                        inventoryWarnModel.MaterialTypeName = inventories[0].MaterialTypeName;
                        inventoryWarnModel.WarnType = 1;
                        inventoryWarnModel.QTY = inventories[0].AvailableQty;
                        Context.TInventoryWarn.Add(inventoryWarnModel);
                    }
                    else
                    {
                        foreach (var item in InventoryWarn)
                        {
                            //item.MaterialId = inventories[0].MaterialId;
                            //item.MaterialCode = inventories[0].MaterialCode;
                            //item.MaterialName = inventories[0].MaterialName;
                            //item.MaterialTypeName = inventories[0].MaterialTypeName;
                            item.QTY = inventories[0].AvailableQty;
                            item.WarnType = 1;
                            Context.TInventoryWarn.Update(item);
                        }

                    }
                    if (Context.SaveChanges() <= 0)
                    {
                        return false;
                    }
                }


                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// 带出所有器材
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetMaterialAll(out int totalCount, string? mname, int? materialCategoryId, int pageIndex, int pageSize)
        {
            totalCount = 0;
            List<TInventory> list = Context.TInventory.ToList();
            if (mname != null)
            {
                list = list.Where(x => x.MaterialName.Contains(mname)).ToList();
            }
            if (materialCategoryId != 0)
            {
                list = list.Where(x => x.MaterialCategoryId == materialCategoryId).ToList();
            }

            totalCount = list.Count();
            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 根据器材ID带出器材其他信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TMaterialSelDto GetMaterialById(int id)
        {

            var TMaterialList = Context.TMaterial.Find(id);

            var TInventoryList = Context.TInventory.Where(x => x.MaterialCode == TMaterialList.Code).FirstOrDefault();
            if (TInventoryList == null)
            {
                return null;
            }
            var Tcellitem = Context.TCells.Where(x => x.Id == TInventoryList.LocationId).FirstOrDefault();

            TMaterialSelDto item = new TMaterialSelDto
            {
                Name = TMaterialList.Name,
                ModelSpec = TMaterialList.ModelSpec,
                Id = TMaterialList.Id,
                Code = TMaterialList.Code,
                ParentCode = TMaterialList.ParentCode,
                TypeId = TMaterialList.TypeId,
                QualityState = TMaterialList.QualityState,
                UnitId = TMaterialList.UnitId,
                UnitName = TMaterialList.UnitName,
                Remark = TMaterialList.Remark,
                MaterialCategoryId = TMaterialList.MaterialCategoryId,
                MaterialCategoryCode = TMaterialList.MaterialCategoryCode,
                MaterialCategoryName = TMaterialList.MaterialCategoryName,
                MaterialGroupId = TMaterialList.MaterialGroupId,
                ReceivedQty = TMaterialList.ReceivedQty,
                Qty = TMaterialList.Qty,
                ReceivePrice = TMaterialList.ReceivePrice,
                CreateUserId = TMaterialList.CreateUserId,
                CreateUserName = TMaterialList.CreateUserName,
                CreateDate = TMaterialList.CreateDate,
                ModifyUserId = TMaterialList.ModifyUserId,
                ModifyUserName = TMaterialList.ModifyUserName,
                ModifyDate = TMaterialList.ModifyDate,
                TInventoryQty = Context.TInventory.Where(x => x.MaterialCode == TMaterialList.Code).Select(x => x.AvailableQty).FirstOrDefault(),
                TcellId = Tcellitem.Id,
                TcellName = Tcellitem.Name,
                TcellCode = Tcellitem.Code,

            };

            return item;
        }

        /// <summary>
        /// 添加出库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddTShippingOrderDetail(GroupShippingOrderDto m, out string message)
        {
            message = "";
            //判断物料是否存在
            foreach (var item in m.shippingLockCells)
            {
                var IsExits = MaterialDoesItExist(item.MaterialCode);
                if (!IsExits)
                {
                    message = "填写的物料不存在，无法出库";
                    return false;

                }
            }

            //判断当前供应商是否存在
            var customers = Context.TCustomers.AsNoTracking().FirstOrDefault(x => x.Code == m.SupplierCode);
            if (customers != null)
            {
                m.SupplierId = customers.Id;
                m.SupplierName = customers.Name;
                //修改已有的
                customers.Name = m.SupplierName;
                customers.Contact = m.Contact;
                customers.ContactMobile = m.ContactMobile;
                customers.ModifyDate = DateTime.Now;
                customers.ModifyUserId = m.NowUserId;
                customers.ModifyUserName = m.NowUserName;
                Context.TCustomers.Update(customers);
            }
            else
            {
                TSupplier customerss = new TSupplier();
                customerss.Code = m.SupplierCode;
                customerss.Name = m.SupplierName;
                customerss.Contact = m.Contact;
                customerss.ContactMobile = m.ContactMobile;
                customerss.CreateDate = DateTime.Now;
                customerss.CreateUserId = m.NowUserId;
                customerss.CreateUserName = m.NowUserName;
                Context.TSuppliers.Add(customerss);
            }

            TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
            shippingOrderDetail.BillType = m.BillType;
            shippingOrderDetail.OrderSn = m.OrderSn;
            shippingOrderDetail.RelevanceOrderSn = m.RelevanceOrderSn;
            shippingOrderDetail.Agent = m.Agent;
            shippingOrderDetail.SupplierId = m.SupplierId;
            shippingOrderDetail.SupplierCode = m.SupplierCode;
            shippingOrderDetail.SupplierName = m.SupplierName;
            shippingOrderDetail.Contact = m.Contact;
            shippingOrderDetail.ContactMobile = m.ContactMobile;
            shippingOrderDetail.ShippingVoucher = m.ShippingVoucher;
            shippingOrderDetail.CreateDate = DateTime.Now;
            shippingOrderDetail.Remark = m.Remark;
            foreach (var item in m.File)
            {
                TShppingOrderDetailFile shppingOrderDetailFile = new()
                {
                    ShippingOrderSn = m.OrderSn,
                    FileUrl = item.url,
                    FileName = item.name
                };
                Context.TShppingOrderDetailFile.Add(shppingOrderDetailFile);

            }
            if (customers == null)
            {
                TCustomer customer = new TCustomer();
                customer.Name = m.SupplierName;
                customer.Code = m.SupplierCode;
                customer.Contact = m.Contact;
                customer.ContactMobile = m.ContactMobile;
                customer.CreateDate = DateTime.Now;
                customer.CreateUserId = m.CreateUserId;
                customer.CreateUserName = m.CreateUserName;
                Context.TCustomers.Add(customer);
                if(Context.SaveChanges() <= 0)
                {
                    message = "添加供应商失败";
                    return false;
                }


             }

            #region 审计字段
            shippingOrderDetail.CreateUserId = m.NowUserId;
            shippingOrderDetail.CreateUserName = m.NowUserName;
            #endregion
            Context.TShippingOrderDetails.Add(shippingOrderDetail);
            if (Context.SaveChanges() > 0)
            {
                foreach (var item in m.shippingLockCells)
                {
                    TShippingLockCell shippingLockCell = new TShippingLockCell();
                    shippingLockCell.OrderDetailId = shippingOrderDetail.Id;
                    shippingLockCell.MaterialCategoryId = item.MaterialCategoryId;
                    shippingLockCell.MaterialCategoryName = item.MaterialCategoryName;
                    shippingLockCell.MaterialCode = item.MaterialCode;
                    shippingLockCell.MaterialId = item.MaterialId;
                    shippingLockCell.MaterialName = item.MaterialName;
                    shippingLockCell.MaterialCode = item.MaterialCode;
                    shippingLockCell.ModelSpec = item.ModelSpec;
                    shippingLockCell.QualityState = item.QualityState;
                    if(item.QualityState == 0)
                    {
                        shippingLockCell.QualityStateName = "新品";
                    }else if(item.QualityState == 1)
                    {
                        shippingLockCell.QualityStateName = "堪用品";
                    }else if(item.QualityState == 2)
                    {
                        shippingLockCell.QualityStateName = "待修品";
                    }
                    else
                    {
                        shippingLockCell.QualityStateName = "废品";
                    }
                    shippingLockCell.MaterialGroupCode = item.MaterialGroupCode;
                    shippingLockCell.UnitName = item.UnitName;

                    if (item.UnitId != null && item.UnitId > 0)
                    {
                        var unitobj = Context.TDictItems.Find(item.UnitId);
                        if (unitobj != null)
                        {
                            shippingLockCell.UnitId = unitobj.Id;
                            shippingLockCell.UnitName = unitobj.ItemName;
                        }
                    }
                    shippingLockCell.CellCode = item.CellCode;
                    shippingLockCell.CellName = item.CellName;
                    shippingLockCell.Price = item.Price;
                    shippingLockCell.TotalPrice = item.TotalPrice;
                    shippingLockCell.OutQty = item.OutQty;
                    shippingLockCell.InventoryQty = item.InventoryQty;

                    Context.TShippingLockCells.Add(shippingLockCell);
                }
            }
            Context.TShippingOrderDetails.Update(shippingOrderDetail);
            return Context.SaveChanges() > 0;

        }


        /// <summary>
        /// 检验是否存在此物料
        /// </summary>
        /// <param name="MaterialCode"></param>
        /// <returns></returns>
        public bool MaterialDoesItExist(string MaterialCode)
        {

            var InventoryList = Context.TInventories.Where(x => x.MaterialCode == MaterialCode).ToList();
            if (InventoryList == null || InventoryList.Count <= 0)
            {
                return false;
            }
            return true;
        }



        /// <summary>
        /// 删除出库表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DeleteTShippingOrderDetail(string OrderSn)
        {
            //using var tran = Context.Database.BeginTransaction();
            //try
            //{
            //    var deleteModel = Context.TShippingOrderDetails.Find(id);
            //    var delShip = Context.TShippingLockCells.Where(s => s.OrderDetailId == id);
            //    var updInvList = new List<TInventory>();
            //    if (deleteModel != null && delShip != null)
            //    {
            //        Context.TShippingOrderDetails.Remove(deleteModel);
            //        //删除被锁定的仓位信息表
            //        Context.TShippingLockCells.RemoveRange(delShip);
            //        foreach (var item in delShip)
            //        {
            //            var invs = Context.TInventory.Find(item.InventoryId);
            //            if (invs != null)
            //            {
            //                invs.Status = 1;
            //                updInvList.Add(invs);
            //            }
            //        }
            //        Context.TInventory.UpdateRange(updInvList);
            //        if (Context.SaveChanges() > 0)
            //        {
            //            tran.Commit();
            //            return true;
            //        }
            //        return false;
            //    }
            //    else
            //    {
            //        // 找不到对应的记录，返回删除失败
            //        //事务回滚
            //        tran.Rollback();
            //        return false;
            //    }

            //}
            //catch (Exception ex)
            //{
            //    //事务回滚
            //    tran.Rollback();
            //    // 处理异常，如记录日志等
            //    return false;
            //}
            var sobj = Context.TShippingOrderDetails.AsNoTracking().Where(x => x.OrderSn == OrderSn);
            if (sobj.Any())
            {
                Context.TShippingOrderDetails.RemoveRange(sobj);
            }
            return Context.SaveChanges() > 0;
        }

        // 根据OrderSn查询ID
        private List<int> GetTShippingOrderDetailId(string OrderSn)
        {
            List<int> listInt = new List<int>();

            var list = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn);

            if (list == null)
            {
                return listInt;
            }
            foreach (var item in list)
            {
                listInt.Add(item.Id);
            }
            return listInt;
        }


        /// <summary>
        /// 删除出库表  多个物料版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DeleteTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                var deleteModel = Context.TShippingOrderDetails.Where(x => x.OrderSn == model.OrderSn);
                // 根据OrderSn查询ID
                var list = GetTShippingOrderDetailId(model.OrderSn);


                foreach (var TShippingLockCellsDetilsId in list)
                {
                    var delShip = Context.TShippingLockCells.Where(s => s.OrderDetailId == TShippingLockCellsDetilsId);
                    var updInvList = new List<TInventory>();
                    if (deleteModel != null && delShip != null)
                    {
                        foreach (var item in deleteModel)
                        {
                            var sta = Context.TShippingOrderDetails.Remove(item);
                            if (sta == null)
                            {
                                tran.Rollback();
                                return false;
                            }
                        }
                        //删除被锁定的仓位信息表
                        Context.TShippingLockCells.RemoveRange(delShip);
                        //bool result =  Context.SaveChanges()>0;
                        //if (!result)
                        //{
                        //    tran.Rollback();
                        //}

                        foreach (var item in delShip.ToList())
                        {
                            var invs = Context.TInventory.Find(item.InventoryId);
                            if (invs != null)
                            {
                                invs.Status = 1;
                                updInvList.Add(invs);
                            }
                        }
                        Context.TInventory.UpdateRange(updInvList);

                    }
                    else
                    {
                        // 找不到对应的记录，返回删除失败
                        //事务回滚
                        tran.Rollback();
                        return false;
                    }
                }
                if (Context.SaveChanges() > 0)
                {
                    tran.Commit();
                    return true;
                }
                return false;

            }
            catch (Exception ex)
            {
                //事务回滚
                tran.Rollback();
                // 处理异常，如记录日志等
                return false;
            }
        }

        /// <summary>
        /// 修改出库单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTShippingOrderDetail(GroupShippingOrderDto m)
        {
            //var shippingLockCells = Context.TShippingLockCells.Where(x => x.OrderDetailId == m.Id).ToList();
            //if (shippingLockCells.Count > 0)
            //{
            //    Context.TShippingLockCells.RemoveRange(shippingLockCells);
            //    if (Context.SaveChanges() <= 0)
            //    {
            //        return false;
            //    }
            //}
            //判断当前供应商是否存在
            var suppobj = Context.TSuppliers.AsNoTracking().FirstOrDefault(x => x.Code == m.SupplierCode);
            if (suppobj != null)
            {
                //m.SupplierId = suppobj.Id;
                //m.SupplierName = suppobj.Name;
                //修改已有的
                suppobj.Name = m.SupplierName;
                suppobj.Contact = m.Contact;
                suppobj.ContactMobile = m.ContactMobile;
                suppobj.ModifyDate = DateTime.Now;
                suppobj.ModifyUserId = m.NowUserId;
                suppobj.ModifyUserName = m.NowUserName;
                Context.TSuppliers.Update(suppobj);
            }
            else
            {
                TSupplier supplier = new TSupplier();
                supplier.Code = m.SupplierCode;
                supplier.Name = m.SupplierName;
                supplier.Contact = m.Contact;
                supplier.ContactMobile = m.ContactMobile;
                //supplier.CreateDate = DateTime.Now;
                supplier.CreateUserId = m.NowUserId;
                supplier.CreateUserName = m.NowUserName;
                Context.TSuppliers.Add(supplier);
            }

            TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
            shippingOrderDetail.Id = m.Id;
            shippingOrderDetail.BillType = m.BillType;
            shippingOrderDetail.OrderSn = m.OrderSn;
            shippingOrderDetail.RelevanceOrderSn = m.RelevanceOrderSn;
            shippingOrderDetail.Agent = m.Agent;
            shippingOrderDetail.SupplierId = m.SupplierId;
            shippingOrderDetail.SupplierCode = m.SupplierCode;
            shippingOrderDetail.SupplierName = m.SupplierName;
            shippingOrderDetail.Contact = m.Contact;
            shippingOrderDetail.ContactMobile = m.ContactMobile;
            shippingOrderDetail.ShippingVoucher = m.ShippingVoucher;
            shippingOrderDetail.CreateDate = DateTime.Now;
            shippingOrderDetail.CreateUserId = m.CreateUserId;
            shippingOrderDetail.CreateUserName = m.CreateUserName;
            shippingOrderDetail.Remark = m.Remark;
            foreach (var shippingFile in m.File)
            {
                TShppingOrderDetailFile shppingOrderDetailFile = new()
                {
                    ShippingOrderSn = m.OrderSn,
                    FileUrl = shippingFile.url,
                    FileName = shippingFile.name
                };
                Context.TShppingOrderDetailFile.Add(shppingOrderDetailFile);
            }
            var shipplocklist = Context.TShippingLockCells.Where(x => x.OrderDetailId == m.Id);
            if (shipplocklist.Any())
            {
                Context.TShippingLockCells.RemoveRange(shipplocklist);
                if (Context.SaveChanges() <= 0)
                {
                    return false;
                };
            }

            foreach (var item in m.shippingLockCells)
            {
                TShippingLockCell shippingLockCell = new TShippingLockCell();
                shippingLockCell.OrderDetailId = shippingOrderDetail.Id;
                shippingLockCell.MaterialCategoryId = item.MaterialCategoryId;
                shippingLockCell.MaterialCategoryName = item.MaterialCategoryName;
                shippingLockCell.MaterialCode = item.MaterialCode;
                shippingLockCell.MaterialId = item.MaterialId;
                shippingLockCell.MaterialName = item.MaterialName;
                shippingLockCell.MaterialCode = item.MaterialCode;
                shippingLockCell.ModelSpec = item.ModelSpec;
                shippingLockCell.QualityState = item.QualityState;
                shippingLockCell.InventoryQty = item.InventoryQty;
                shippingLockCell.UnitName = item.UnitName;
                shippingLockCell.MaterialGroupCode = item.MaterialGroupCode;
                if (item.UnitId != null && item.UnitId > 0)
                {
                    var unitobj = Context.TDictItems.Find(item.UnitId);
                    if (unitobj != null)
                    {
                        shippingLockCell.UnitId = unitobj.Id;
                        shippingLockCell.UnitName = unitobj.ItemName;
                    }
                }
                shippingLockCell.CellCode = item.CellCode;
                shippingLockCell.Price = item.Price;
                shippingLockCell.TotalPrice = item.TotalPrice;
                shippingLockCell.OutQty = item.OutQty;
                Context.TShippingLockCells.Add(shippingLockCell);
                if (Context.SaveChanges() <= 0)
                {
                    return false;
                };
            }

            #region 审计字段
            shippingOrderDetail.ModifyUserId = m.NowUserId;
            shippingOrderDetail.ModifyUserName = m.NowUserName;
            shippingOrderDetail.ModifyDate = DateTime.Now;

            #endregion
            Context.TShippingOrderDetails.Update(shippingOrderDetail);
            return Context.SaveChanges() > 0;
        }


        /// <summary>
        /// 修改出库单  多物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTshippingOrderDetailPlus(TShippingOrderDetailPlusDTO models)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                int id = 0;
                foreach (var model in models.ShippingOrderDetailPlusLockCellDTOs)
                {
                    //var updateModel = Context.TShippingOrderDetails.FirstOrDefault(x => x.OrderSn ==  models.OrderSn);
                    var updateModel = Context.TShippingOrderDetails.FirstOrDefault(x => x.Id == model.TShippingLockCellsId);
                    if (updateModel == null)
                    {
                        throw new Exception("要更新的记录不存在");
                    }

                    try
                    {
                        //订单号
                        //单据类型
                        //合同号
                        //物料分类 优先级为顶级 默认为0
                        //物料名称
                        var material = Context.TMaterials.Find(model.MaterialId);
                        if (material != null)
                        {
                            //updateModel.MaterialId = material.Id;
                            //updateModel.MaterialCode = material.Code;
                            //updateModel.MaterialName = material.Name;
                            //updateModel.MaterialTypeCode = material.TypeCode;
                            //updateModel.UnitId = material.UnitId;
                            //updateModel.UnitName = material.UnitName;
                        }

                        //// 物料批次信息
                        //// 根据 MaterialId 和 MaterialName 查询对应的物料批次记录
                        //var materialkey = Context.TMaterialKeys.FirstOrDefault(m =>
                        //    m.MaterialId == model.MaterialId && m.MaterialName == model.MaterialName);
                        //if (materialkey != null)
                        //{
                        //    updateModel.BatchNo = materialkey.BatchNo;
                        //}


                        //客户
                        var cust = Context.TCustomers.Find(models.CustomerId);
                        if (cust != null)
                        {
                            updateModel.CreateUserName = cust.CreateUserName;
                        }

                        updateModel.BillType = models.BillType;
                        Context.TShippingOrderDetails.Update(updateModel);
                        Context.SaveChanges();


                    }
                    catch (Exception)
                    {
                        //事务回滚
                        tran.Rollback();
                        throw;
                    }
                }
                //无异常提交事务
                tran.Commit();
                return true;
            }
        }

        /// <summary>
        /// 根据Id查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TShippingOrderDetail GetByIdTShippingOrderDetail(string OrderSn)
        {
            TShippingOrderDetail listDetail = new TShippingOrderDetail();
            // 根据ID查找出库管理记录
            var shippingOrderDetail = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();

            // 如果找到了出库管理记录
            if (shippingOrderDetail != null)
            {
                //if (OrderSn.Substring(0, 1).Contains("R"))
                //{
                if (OrderSn.Substring(0, 1).Contains("R"))
                {
                    TShippingLockCell shippingLockCell = new TShippingLockCell();
                    List<TReceivingOrderDetail> receivingOrderDetails = Context.TReceivingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();
                    foreach (var item in receivingOrderDetails)
                    {
                        //listDetail.OrderSn = dto.OrderSn;
                        //listDetail.RelevanceOrderSn = dto.RelevanceOrderSn;
                        //listDetail.BillType = dto.BillType;
                        //listDetail.Agent = dto.Agent;
                        //listDetail.SupplierId = dto.SupplierId;
                        //listDetail.SupplierCode = dto.SupplierCode;
                        //listDetail.SupplierName = dto.SupplierName;
                        //listDetail.Contact = dto.Contact;
                        //listDetail.ContactMobile = dto.ContactMobile;
                        //listDetail.Remark = dto.Remark;
                        shippingLockCell.MaterialCategoryId = item.MaterialCategoryId;
                        shippingLockCell.MaterialCategoryName = item.MaterialCategoryName;
                        shippingLockCell.MaterialCategoryCode = item.MaterialCategoryCode;
                        shippingLockCell.MaterialId = item.MaterialId;
                        shippingLockCell.MaterialName = item.MaterialName;
                        shippingLockCell.MaterialCode = item.MaterialCode;
                        shippingLockCell.ModelSpec = item.ModelSpec;
                        shippingLockCell.QualityState = item.QualityState;
                        shippingLockCell.UnitId = item.UnitId;
                        shippingLockCell.UnitName = item.UnitName;
                        shippingLockCell.OutQty = item.Qty;
                        shippingLockCell.Price = item.Price;
                        shippingLockCell.TotalPrice = item.Price * item.Qty;
                        //listDetail.OrderSn = item.OrderSn;
                        //listDetail.BillType = item.BillType;
                        //listDetail.Status = item.Status;
                        //listDetail.SourceType = item.SourceType;
                        //listDetail.CreateUserId = item.CreateUserId;
                        //listDetail.CreateUserName = item.CreateUserName;
                        //listDetail.CreateDate = item.CreateDate;
                        //listDetail.ModifyUserId = item.ModifyUserId;
                        //listDetail.ModifyUserName = item.ModifyUserName;
                        //listDetail.ModifyDate = item.ModifyDate;
                        //listDetail.SupplierName =   item.SupplierName;
                        //listDetail.SupplierId = item.SupplierId;
                        //listDetail.Remark = item.Remark;
                        listDetail.shippingLockCells.Add(shippingLockCell);

                    }
                }
                else if (OrderSn.Substring(0, 1).Contains("C"))
                {
                    var fileList = Context.TShppingOrderDetailFile.Where(x => x.ShippingOrderSn == OrderSn);
                    List<FileClass> files = new List<FileClass>();
                    foreach (var item1 in fileList)
                    {
                        FileClass file = new FileClass();
                        file.name = item1.FileName;
                        file.url = item1.FileUrl;
                        files.Add(file);
                    }
                    foreach (var item in shippingOrderDetail)
                    {
                        // 查询对应的货位锁定明细记录
                        List<TShippingLockCell> lockCells = Context.TShippingLockCells.Where(c => c.OrderDetailId == item.Id).ToList();
                        if (lockCells.Any())
                        {

                            item.shippingLockCells = lockCells;
                            listDetail = item;
                            listDetail.FileUrl = files;
                        }
                        else
                        {
                            listDetail = item;
                            listDetail.FileUrl = files;
                        }
                    }
                }
                else
                {
                    return null;
                }
                //}


            }

            return listDetail;
        }

        /// <summary>
        /// 根据OrderSn查询
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public List<TShippingOrderDetail> GetByOrderSnTShipping(string OrderSn)
        {
            var shippingOrderList = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();

            // 如果找到了出库管理记录
            if (shippingOrderList != null)
            {
                foreach (var item in shippingOrderList)
                {
                    // 查询对应的货位锁定明细记录
                    var lockCells = Context.TShippingLockCells.Where(c => c.OrderDetailId == item.Id).ToList();
                    if (lockCells.Any())
                    {

                        shippingOrderList[0].shippingLockCells = lockCells;
                    }
                }

            }

            return shippingOrderList;
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdTShippingOrderDetailState(ReceivingOrderDetailDto model)
        {
            var robjs = Context.TShippingOrderDetails.Where(s => s.OrderSn == model.OrderSN).ToList();

            if (robjs != null && robjs.Count() != 0)
            {
                foreach (var robj in robjs)
                {
                    switch (model.state)
                    {
                        case 0:
                            var uobj = Context.TUsers.FirstOrDefault(x =>
                                x.Id == model.NowUserId);
                            if (uobj != null)
                            {
                                robj.SubmitUserId = model.NowUserId;
                                robj.SubmitUserName = model.NowUserRealName;
                                robj.SubmitDate = DateTime.Now;

                                //修改为：审核通过
                                robj.Status = 2;
                                Context.TShippingOrderDetails.Update(robj);
                                break;
                            }

                            return false;

                        case 1:
                            break;

                        case 2:
                            robj.ModifyUserId = model.NowUserId;
                            robj.ModifyUserName = model.NowUserRealName;
                            robj.ModifyDate = DateTime.Now;
                            //修改为：作业中
                            robj.Status = 3;
                            Context.TShippingOrderDetails.Update(robj);
                            break;

                        case 3:
                            robj.ModifyUserId = model.NowUserId;
                            robj.ModifyUserName = model.NowUserRealName;
                            robj.ModifyDate = DateTime.Now;
                            //修改为：已完成
                            robj.Status = 4;
                            Context.TShippingOrderDetails.Update(robj);
                            break;

                        default:
                            break;
                    }
                }

                return Context.SaveChanges() > 0;
            }

            return false;
        }

        #region 一键选定弃用
        ///// <summary>
        ///// 一键选定
        ///// </summary>
        ///// <param name="materid">物料Id</param>
        ///// <param name="count">出库数量</param>
        ///// <param name="whid">库房Id</param>
        ///// <param name="areaid">库区Id</param>
        ///// <param name="supid">供应商Id</param>
        ///// <param name="owid">货主Id</param>
        ///// <returns></returns>
        //public List<TInventory> GetAllTShippingLockCell(int materid, int count, int whid, int areaid, int supid,
        //    int owid)
        //{
        //    //var shippinglockcell=Context.TShippingLockCells.Where(x=>x.)
        //    var ilist = Context.TInventories.Where(x => x.MaterialId == materid);
        //    ilist = ilist.Where(x => x.AvailableQty != 0 && x.Status == 1);
        //    //ilist = ilist.OrderBy(x => x.BatchNo);
        //    //库房
        //    if (whid != 0)
        //    {
        //        ilist = ilist.Where(x => x.WarehouseId == whid);
        //    }



        //    //供应商
        //    if (supid != 0)
        //    {
        //        ilist = ilist.Where(x => x.SupplierId == supid);
        //    }

        //    List<TInventory> list = new List<TInventory>();
        //    //收货的数量
        //    foreach (var item in ilist)
        //    {
        //        //decimal? outqty = count - item.AvailableQty;
        //        if (count == item.AvailableQty)
        //        {
        //            //如果要出库的数量等于该库存的数量则直接返回
        //            item.OutQty = item.AvailableQty;
        //            list.Add(item);
        //            return list;
        //        }
        //        else if (count > item.AvailableQty)
        //        {
        //            item.OutQty = item.AvailableQty;
        //            list.Add(item);
        //            count = Convert.ToInt32(count - item.OutQty);
        //        }
        //        else if (count < item.AvailableQty)
        //        {
        //            item.OutQty = count;
        //            list.Add(item);
        //            return list;
        //        }
        //    }

        //    return list;
        //}
        ///// <summary>
        ///// 一键选定(弃用)
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
        //public bool SelectTShippingOrderDetail(TShippingOrderDetail model)
        //{
        //    //var OrderDetail = Context.TShippingOrderDetails.FirstOrDefault(m =>
        //    //    m.MaterialId == model.MaterialId &&
        //    //    m.WarehouseId == model.WarehouseId && m.Qty == model.Qty);
        //    //if (OrderDetail == null)
        //    //{
        //    //    return false; // 找不到对应的出库管理记录，选定失败
        //    //}
        //    //// 设置其他相关字段值，例如物料分类、物料名称、物料批次等

        //    //OrderDetail.MaterialName = model.MaterialName;
        //    //OrderDetail.WarehouseName = model.WarehouseName;
        //    //OrderDetail.Qty = model.Qty;
        //    //OrderDetail.MaterialCode = model.MaterialCode;

        //    //OrderDetail.ContractNo = model.ContractNo;
        //    //OrderDetail.BillType = model.BillType;

        //    //OrderDetail.SupplierId = model.SupplierId;
        //    //OrderDetail.SupplierName = model.SupplierName;
        //    //OrderDetail.AuditUserId = model.AuditUserId;
        //    //OrderDetail.AuditUserName = model.AuditUserName;
        //    //OrderDetail.Status = model.Status;
        //    //// 保存修改
        //    //Context.SaveChanges();

        //    //// 创建新的TShippingLockCell实例并赋值
        //    //List<TShippingLockCell> lockCells = new List<TShippingLockCell>();

        //    ////库位
        //    //var Cells = Context.TCells.FirstOrDefault(m => lockCells.Any(x => x.CellId == m.Id));
        //    ////出库详细单
        //    //var orderDetail =
        //    //    Context.TShippingOrderDetails.FirstOrDefault(m => lockCells.Any(x => x.OrderDetailId == m.Id));
        //    ////库存
        //    //var inventory = Context.TInventories.FirstOrDefault(m => lockCells.Any(x => x.InventoryId == m.Id));

        //    //if (new TShippingLockCell().InventoryQty >= model.Qty)
        //    //{
        //    //    var lockCell = new TShippingLockCell
        //    //    {
        //    //        MaterialId = OrderDetail.MaterialId,
        //    //        MaterialCode = model.MaterialCode,
        //    //        MaterialName = model.MaterialName,
        //    //        OrderDetailId = model.Id,
        //    //        OutQty = OrderDetail.Qty,
        //    //        CellName = Cells.Name,
        //    //        WhId = OrderDetail.WarehouseId,
        //    //        InventoryId = inventory.Id,
        //    //        InventoryQty = inventory.AvailableQty,
        //    //    };
        //    //    lockCells.Add(lockCell);
        //    //}
        //    //else
        //    //{
        //    //    // 根据出库数量创建多个TShippingLockCell实例并添加到列表中
        //    //    decimal? remainingQty = model.Qty;
        //    //    decimal? stockQuantity = inventory.AvailableQty;
        //    //    while (remainingQty > 0)
        //    //    {
        //    //        var lockCellss = new TShippingLockCell
        //    //        {
        //    //            MaterialId = OrderDetail.MaterialId,
        //    //            MaterialCode = model.MaterialCode,
        //    //            MaterialName = model.MaterialName,
        //    //            OrderDetailId = model.Id,
        //    //            OutQty = OrderDetail.Qty,
        //    //            CellName = Cells.Name,
        //    //            WhId = OrderDetail.WarehouseId,
        //    //            InventoryId = inventory.Id,
        //    //            InventoryQty = Math.Min(stockQuantity ?? 0, remainingQty ?? 0),
        //    //        };

        //    //        lockCells.Add(lockCellss);

        //    //        remainingQty -= stockQuantity; // 更新剩余数量
        //    //    }
        //    //}

        //    //Context.TShippingLockCells.AddRange(lockCells);

        //    return false;
        //    //return Context.SaveChanges() > 0;
        //}

        ///// <summary>
        ///// 一键选定（弃用）
        ///// </summary>
        ///// <param name="qty"></param>
        ///// <param name="inventoryId"></param>
        ///// <param name="whId"></param>
        ///// <param name="materialId"></param>
        ///// <returns></returns>
        ///// <exception cref="NotImplementedException"></exception>
        //public List<TShippingLockCell> GetAllTShippingLockCell(TShippingOrderDetail model)
        //{
        //    //// 校验物料Id是否为空或无效
        //    //if (model.MaterialId <= 0)
        //    //{
        //    //    throw new ArgumentException("请选择物料");
        //    //}

        //    //// 校验数量是否为空或无效
        //    //if (model.Qty <= 0)
        //    //{
        //    //    throw new ArgumentException("请选择出库数量");
        //    //}

        //    //if (model.WarehouseId <= 0)
        //    //{
        //    //    throw new ArgumentException("请选择仓库");
        //    //}

        //    ////if (model.MaterialId <= 0)
        //    ////{
        //    ////    throw new ArgumentException("请选择物料");
        //    ////}

        //    //List<TShippingLockCell> selectedCells = new List<TShippingLockCell>();
        //    //// 查询仓位明细表中符合条件的数据
        //    //var query = from cell in Context.TShippingLockCells
        //    //            where cell.InventoryQty >= model.Qty && cell.WhId == model.WarehouseId &&
        //    //                  cell.MaterialId == model.MaterialId

        //    //            select cell;

        //    //// 遍历查询结果，并将符合条件的仓位明细添加到返回列表中
        //    //foreach (var cell in query)
        //    //{
        //    //    selectedCells.Add(cell);
        //    //}

        //    //return selectedCells;
        //    return null;
        //}
        #endregion

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="status"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShippingOrderDetail> GetAllTShippingOrderDetail(string? StartTime, string? EndTime, int? billType, int? status, int? warehouseid, string rolecode, int pageIndex, int pageSize, out int totalCount)
        {
            // 创建查询的基础列表，包含所有的 TShippingOrderDetail 记录
            var query = Context.TShippingOrderDetails.AsQueryable();

            if (StartTime != null && EndTime != null)
            {
                string StartdateString = StartTime;
                DateTime Startdate = DateTime.Parse(StartdateString);
                string EnddateString = EndTime;
                DateTime Enddate = DateTime.Parse(EnddateString);
                query = query.Where(x => x.CreateDate >= Startdate && x.CreateDate <= Enddate);

            }

            if (billType > 0)
            {
                query = query.Where(x => x.BillType == billType);
            }

            if (status < 8)
            {
                query = query.Where(x => x.Status == status);
            }

            bool Examine = false;
            if (!string.IsNullOrEmpty(rolecode) && rolecode == "admin")
                Examine = true;
            List<TShippingOrderDetail> shipplist = new List<TShippingOrderDetail>();
            foreach (var item in query.ToList())
            {
                item.ExamineState = Examine;
                shipplist.Add(item);
            }
            // 获取符合条件的总记录数
            totalCount = shipplist.Count();

            // 对结果进行排序和分页
            var resultList = shipplist.OrderByDescending(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return resultList;
        }

        /// <summary>
        /// 根据物料Id返回批次号和数量
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public BatchNoMaxCount GetMaterialIdById(int materialId, string batchNO = null, int? qualityState = null, string warehouseCode = "", string areaCode = "", int? ownerId = null, int? supplierId = null, string produceFactory = "")
        {
            //数量
            try
            {
                //BatchNoMaxCount bc = new BatchNoMaxCount();

                //////找出该库存的所有批次号
                ////var materialKeyQuery = Context.TMaterialKeys;
                //var inventoryQuery = Context.TInventories;

                //var list=(from mk in materialKeyQuery
                //         join inv in inventoryQuery
                //         on mk.Id equals inv.MaterialKeyId
                //         where mk.MaterialId == materialId
                //         select new BatchNoMaxCountDTO ( mk.BatchNo,mk.Id)).Distinct().ToList();
                //bc.materialKeys = list;

                ////仓位状态 货架状态 巷道状态
                //var cellQuery = Context.TCells;
                //var shelfQuery = Context.TShelves;
                //var TInventoryQuery = (from inv in Context.TInventories
                //                       join cell in cellQuery
                //                       on inv.LocationId equals cell.Id
                //                       join slf in shelfQuery
                //                       on cell.ShelfId equals slf.Id                                   
                //                       where cell.Status == 1 && slf.Status == 1
                //                       select inv
                //                      ).ToList();

                //var invList = TInventoryQuery.Where(t => t.MaterialId == materialId && t.Status == 1 && t.IsLock == false).ToList();
                //if (!string.IsNullOrEmpty(batchNO))
                //{
                //    invList = invList.Where(t => t.BatchNo == batchNO).ToList();
                //}
                //if (qualityState != null)
                //{
                //    invList = invList.Where(t => t.QualityState == qualityState).ToList();
                //}
                //if (!string.IsNullOrEmpty(warehouseCode))
                //{
                //    invList = invList.Where(t => t.WarehouseCode == warehouseCode).ToList();
                //}
                //if (!string.IsNullOrEmpty(areaCode))
                //{
                //    invList = invList.Where(t => t.AreaCode == areaCode).ToList();
                //}
                //if (ownerId > 0)
                //{
                //    invList = invList.Where(t => t.OwnerId == ownerId).ToList();
                //}
                //if (supplierId > 0)
                //{
                //    invList = invList.Where(t => t.SupplierId == supplierId).ToList();
                //}
                //if (!string.IsNullOrEmpty(produceFactory))
                //{
                //    invList = invList.Where(t => t.ProduceFactory.Contains(produceFactory)).ToList();
                //}
                //decimal? sum = invList.Sum(t => t.AvailableQty);

                //List<int?> status = new List<int?>
                //{
                //    (int)EmBillStatus.Create,
                //    (int)EmBillStatus.Submit,
                //    (int)EmBillStatus.Pass,
                //};
                ////一键出库优先级最高
                //var shippingOrderDetailQuery = Context.TShippingOrderDetails.OrderByDescending(t => t.IsOnceOut);
                //var slcOdQuery = (from lockCell in Context.TShippingLockCells
                //                  join od in shippingOrderDetailQuery
                //                  on lockCell.OrderDetailId equals od.Id
                //                  select new { lockCell, od }
                //                ).ToList();
                //var slcOdQueryTest = slcOdQuery.ToList();
                //List<TShippingLockCell> lockCells = slcOdQuery.Select(x => x.lockCell).ToList();
                //List<TShippingOrderDetail> orderDetails = slcOdQuery.Select(x => x.od).ToList();
                //orderDetails = orderDetails.Where(od => od.MaterialId == materialId && status.Contains(od.Status)).ToList();
                //lockCells = lockCells.Where(loc => loc.MaterialId == materialId).ToList();
                //slcOdQuery = (from lockCell in lockCells
                //                join od in orderDetails
                //                on lockCell.OrderDetailId equals od.Id
                //                select new { lockCell, od }
                //        ).ToList();


                ////剔除被锁定的库存
                //var lockInvIdQuery = (from lockCell in lockCells
                //                      join od in orderDetails
                //                      on lockCell.OrderDetailId equals od.Id
                //                      select lockCell.InventoryId
                //            ).Distinct().ToList();
                //int lockInvCount = lockInvIdQuery.Count();
                //if (lockInvCount > 0)
                //{
                //    invList = invList.Where(t => !lockInvIdQuery.ToList().Contains(t.Id)).ToList();
                //}
                ////查出所有匹配的库存
                //List<TInventory> TInventoryList = invList.OrderBy(x => x.LocationDepth)
                //                                        .ThenBy(x => x.InStockShortDate)
                //                                        .ThenByDescending(x => x.AvailableQty)
                //                                        .ThenBy(x => x.LocationLineNo)
                //                                        .ThenBy(x => x.LocationLayerNo)
                //                                        .ThenBy(x => x.LocationColumnNo).ToList();
                ////库存可用数量
                //decimal totalTInventoryCount = TInventoryList.Sum(t => t.AvailableQty.GetValueOrDefault());
                ////当前物料已出库多少

                //bc.MaxCount = totalTInventoryCount;
                return null;

            }
            catch (Exception ex)
            {
                throw ex;
            }

            //BatchNoMaxCount bc = new BatchNoMaxCount();
            ////物料批次
            //var mkobj = Context.TMaterialKeys.FirstOrDefault(x => x.MaterialId == mid);
            ////库存数量
            //var iobj = Context.TInventories.Where(x => x.MaterialId == mid);
            //if (iobj.Count() <= 0)
            //{
            //    return bc;
            //}

            //if (mkobj != null)
            //{
            //    bc.BatchNO.Add(mkobj.BatchNo);
            //}

            //if (iobj != null)
            //{
            //    foreach (var item in iobj.ToList())
            //    {
            //        bc.MaxCount += item.AvailableQty;
            //    }
            //}

            //return bc;
        }

        /// <summary>
        /// 获取商品详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<TShippingGoodsDetail> GetOneTShippingGoodsDetail(int id, int pageIndex, int pageSize, out int totalCount)
        {
            var order = Context.TShippingOrderDetails.Find(id);
            if (order == null)
            {
                totalCount = 0;
                // 订单不存在时返回一个空的列表
                return new List<TShippingGoodsDetail>();
            }
            var details = Context.TShippingGoodsDetails.Where(m => m.OrderDetailId == order.Id).ToList();
            // 获取符合条件的总记录数
            totalCount = details.Count();

            // 对结果进行排序和分页
            var resultList = details.OrderBy(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return resultList;
        }

        public List<TShippingGoodsDetail> GetByNameShippingGoodsDetail(string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var query = Context.TShippingGoodsDetails.AsQueryable();
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(m => m.MaterialName == name);
            }
            totalCount = query.Count();

            // 对结果进行排序和分页
            var resultList = query.OrderBy(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return resultList;
        }

        public List<GetChukuDanDTO> GetAllTShippingOrderDetailPlus(int? billType, int? houseid, string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var listNoPage = Context.TShippingOrderDetails.AsEnumerable();
            if (billType != null)
                listNoPage = listNoPage.Where(s => s.BillType == billType);
            if (houseid != null)
                listNoPage = listNoPage.Where(s => s.WarehouseId == houseid);
            //if (name != null)
            //    listNoPage = listNoPage.Where(s => s.MaterialName == name);
            var items = listNoPage.OrderByDescending(s => s.CreateDate).GroupBy(s => s.OrderSn);
            var list = items.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            totalCount = items.Count();
            List<GetChukuDanDTO> resList = new List<GetChukuDanDTO>();
            foreach (var item in list)
            {
                var key = item.Key;
                var lockCellList = new List<TShippingLockCell>();
                var shippoutList = new List<TShippingOrderDetail>();
                foreach (var value in item)
                {
                    var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == value.Id);
                    foreach (var item1 in lockCell)
                    {
                        lockCellList.Add(item1);
                    }
                    shippoutList.Add(value);
                }
                resList.Add(new GetChukuDanDTO()
                {
                    Status = GetStatus(shippoutList),
                    OrderSn = key,
                    CreateTime = shippoutList[0].CreateDate,
                    //Sum = shippoutList.Sum(s=>s.Qty),
                    CreateUserName = shippoutList[0].CreateUserName,
                    AuditUserName = shippoutList[0].AuditUserName,
                    shippingOrders = lockCellList,
                });
            }
            return resList;
        }
        private string GetStatus(List<TShippingOrderDetail> shippingGoods)
        {
            int status = 4;
            string str = "未知状态";
            foreach (var item in shippingGoods)
            {
                if (item.Status != 4)
                {
                    if (item.Status == 0)
                    {
                        status = 0;
                        break;
                    }
                    else if (item.Status == 1)
                    {
                        status = 1;
                        break;
                    }
                    else if (item.Status == 2)
                    {
                        status = 2;
                        break;
                    }
                    else if (item.Status == 3)
                    {
                        status = 3;
                        break;
                    }
                }
            }
            if (status == 0)
            {
                str = "创建";
                return str;
            }
            else if (status == 1)
            {
                str = "提交";
                return str;
            }
            else if (status == 2)
            {
                str = "审核通过";
                return str;
            }
            else if (status == 3)
            {
                str = "作业中";
                return str;
            }
            else if (status == 4)
            {
                str = "已完成";
                return str;
            }
            return str;
        }

        public List<TShippingOrderDetail> GetTShippingOrder(int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TShippingOrderDetails.ToList();
            totalCount = list.Count;
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(x => x.CreateDate).ToList();
            foreach (var item in list)
            {
                List<TShippingLockCell> shippingLockCell = new List<TShippingLockCell>();
                var shippingLockCellList = Context.TShippingLockCells.Where(x => x.OrderDetailId == item.Id).ToList();
                foreach (var items in shippingLockCellList)
                {
                    shippingLockCell.Add(items);
                }
                item.shippingLockCells = shippingLockCell;

            }

            return list;
        }

        /// <summary>
        /// 关联单号查询
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        public List<TShippingLockCell> GetShippingLockCells(string OrderSn,out string message)
        {
            message = "";
            //TShippingOrderDetail listDetail = new TShippingOrderDetail();
            List<TShippingLockCell> shippingLockCells = new List<TShippingLockCell>();
            // 根据ID查找出库管理记录
            var shippingOrderDetail = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();

            // 如果找到了出库管理记录
            if (shippingOrderDetail != null)
            {
                //if (OrderSn.Substring(0, 1).Contains("R"))
                //{
                if (OrderSn.Substring(0, 1).Contains("R"))
                {
                    List<TReceivingOrderDetail> receivingOrderDetails = Context.TReceivingOrderDetails.Where(x => x.OrderSn == OrderSn).ToList();
                    foreach (var item in receivingOrderDetails)
                    {
                        TShippingLockCell shippingLockCell = new TShippingLockCell();
                        shippingLockCell.MaterialCategoryId = item.MaterialCategoryId;
                        shippingLockCell.MaterialCategoryName = item.MaterialCategoryName;
                        shippingLockCell.MaterialCategoryCode = item.MaterialCategoryCode;
                        shippingLockCell.MaterialId = item.MaterialId;
                        shippingLockCell.MaterialName = item.MaterialName;
                        shippingLockCell.MaterialCode = item.MaterialCode;
                        shippingLockCell.ModelSpec = item.ModelSpec;
                        shippingLockCell.QualityState = item.QualityState;
                        shippingLockCell.UnitId = item.UnitId;
                        shippingLockCell.UnitName = item.UnitName;
                        shippingLockCell.OutQty = item.Qty;
                        shippingLockCell.Price = item.Price;
                        shippingLockCell.MaterialGroupCode = item.MaterialGroupId;
                        var list = Context.TInventories.Where(x => x.MaterialCode == item.MaterialCode).ToList();
                        if(list.Count() <= 0)
                        {
                            message = "入库单中有物料未入库";
                            return null;
                        }
                        shippingLockCell.InventoryQty = list.First().AvailableQty;
                        shippingLockCell.TotalPrice = item.Price * item.Qty;
                        shippingLockCells.Add(shippingLockCell);
                    }
                }
                else if (OrderSn.Substring(0, 1).Contains("C"))
                {
                    List<TShippingLockCell> shippingLock = new List<TShippingLockCell>();
                    foreach (var item in shippingOrderDetail)
                    {
                        // 查询对应的货位锁定明细记录
                        List<TShippingLockCell> lockCells = Context.TShippingLockCells.Where(c => c.OrderDetailId == item.Id).ToList();
                        shippingLock.AddRange(lockCells);
                    }
                    shippingLockCells.AddRange(shippingLock);
                }
                else
                {
                    return null;
                }
                //}


            }

            return shippingLockCells;
        }

        public List<ShippingPositionDto> GetPositionByMaterial(string MaterialCode)
        {
            var list = Context.TInventories.Where(x => x.MaterialCode ==  MaterialCode).ToList();
            List<ShippingPositionDto> shippingPositionDtos = new List<ShippingPositionDto>();
            foreach (var item in list)
            {
                ShippingPositionDto shippingPositionDto = new ShippingPositionDto();
                shippingPositionDto.materialCode = MaterialCode;
                shippingPositionDto.materialName = item.MaterialName;
                shippingPositionDto.positionCode = item.LocationCode;
                shippingPositionDto.positionName = item.LocationName;
                shippingPositionDtos.Add(shippingPositionDto);
            }
            return shippingPositionDtos;
        }


        public List<string> GetAllCellCode(GroupShippingOrderDto model)
        {
            List<TTemporaryTable> temporaryTables = new List<TTemporaryTable>();
            foreach (var item in model.shippingLockCells)
            {
                TTemporaryTable temporaryTable = new TTemporaryTable();
                temporaryTable.CellCode = item.CellCode;
                var cellTable = Context.TCells.FirstOrDefault(x => x.Code == item.CellCode);
                if(cellTable == null)
                {
                    return null;
                }
                temporaryTable.ShelvesCode = cellTable.ShelfCode;
                var shelvesTable = Context.TShelves.FirstOrDefault(x => x.Code == cellTable.ShelfCode);
                if(shelvesTable == null)
                {
                    return null;
                }
                var routewayTable = Context.TRouteways.FirstOrDefault(x => x.Id == shelvesTable.RoutewayId);
                temporaryTable.RoutewayCode = routewayTable.Code;
                temporaryTables.Add(temporaryTable);
            }
            Context.TTemporaryTable.AddRange(temporaryTables);
            if(Context.SaveChanges() <= 0)
            {
                return null;
            }

            List<string> cellCodes = new List<string>();
            foreach (var item in model.shippingLockCells)
            {
                string cellcode = item.CellCode;
                cellCodes.Add(cellcode);
            }
            return cellCodes;
        }
    }
}